package rpc

import (
	"crypto/sha256"
	"encoding/hex"

	"github.com/pkg/errors"

	"ldaccount/internal/conf"
	"ldaccount/internal/service"
	"ldaccount/pkg/is"
	"ldaccount/pkg/log"
	"ldaccount/pkg/lueerror"
)

type Base struct {
	logger log.Factory
	cfg    *conf.Config
}

var base *Base

func InitRpcBase(logger log.Factory, cfg *conf.Config) {
	base = &Base{
		logger: logger,
		cfg:    cfg,
	}
}

// GenJwtToken 生成token
func (b *Base) GenJwtToken(gID, mobile, email, userName string) (string, lueerror.LueError) {
	return service.GetService().GenJwtToken(gID, mobile, email, userName)
}

func (b *Base) VerifyJwtToken(token string) (*service.JwtPayload, lueerror.LueError) {
	return service.GetService().VerifyToken(token)
}

func (b *Base) MobileCheck(mobile string) lueerror.LueError {
	if !is.CNMobile(mobile) {
		return lueerror.InvalidMobile(errors.New("手机号格式错误"))
	}
	return nil
}

func (b *Base) EmailCheck(email string) lueerror.LueError {
	if !is.Email(email) {
		return lueerror.InvalidEmail(errors.New("邮箱格式错误"))
	}
	return nil
}

func (b *Base) EmailMobileCheck(email, mobile string) lueerror.LueError {
	if email != "" {
		errL := b.EmailCheck(email)
		if errL != nil {
			return errL
		}
	}
	if mobile != "" {
		errL := b.MobileCheck(mobile)
		if errL != nil {
			return errL
		}
	}
	return nil
}

// ContainsStr 查询是否在数组中存在
func ContainsStr(a []string, x string) bool {
	for _, n := range a {
		if x == n {
			return true
		}
	}
	return false
}

// SignSha256 sha256 签名计算
func SignSha256(sign string) (string, error) {
	h := sha256.New()
	_, err := h.Write([]byte(sign))
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(h.Sum(nil)), nil
}
